package com.atguigu.myjuc.demo;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//资源类
 class Ticket{
     private int num = 50;
/*    public synchronized void sale(){
        if(num > 0){
            System.out.println(Thread.currentThread().getName()+"\t"+"卖出第："+(num--)+"\t 还剩下："+num);
            *//*try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }*//*
        }
    }*/


    //第二版v2
    private final Lock lock = new ReentrantLock();
    public void sale(){
        lock.lock();
        try {
            if (num > 0){
                System.out.println(Thread.currentThread().getName()+"\t"+"卖出第："+(num--)+"\t 还剩下："+num);
            }
        }finally {
            lock.unlock();
        }
    }
}







public class SaleTicketDemo {
    //juc 小口诀  线程  操作  资源类
    public static void main(String[] args) {//main是程序入口

        //第一版本v1

        Ticket ticket = new Ticket();

        /*new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 50; i++) {
                    ticket.sale();
                }
            }
        },"A").start();
        new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 50; i++) {
                    ticket.sale();
                }
            }
        },"A").start();
        new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 50; i++) {
                    ticket.sale();
                }
            }
        },"A").start();*/

        //第二版 v2 lambalad表达式
        new Thread(()->{for (int i = 1; i < 50; i++) ticket.sale();},"A").start();
        new Thread(()->{for (int i = 1; i < 50; i++) ticket.sale();},"B").start();
        new Thread(()->{for (int i = 1; i < 50; i++) ticket.sale();},"C").start();
    }
}
